package com.lkd.interceptor;


import com.lkd.entity.UserEntity;
import com.lkd.feign.UserService;
import com.lkd.utils.VmThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @Author: cl
 * @Date: 2022/6/7 - 06 - 07
 * @Description:
 */
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {

    //之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的id
        String userId = request.getHeader("userId");
        //非空判断
        Optional<String> optional = Optional.ofNullable(userId);
        if (optional.isPresent()) {
            //非空为true   把用户id放入threadloacl中
            UserEntity user = new UserEntity();
            user.setId(Integer.valueOf(userId));
            VmThreadLocalUtils.setUser(user);
            log.info("用户的id为:{}", userId);

        }
        return true;
    }

    //之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        log.info("清理threadlocal...");
        VmThreadLocalUtils.clear();
    }
}
